package net.apps123.soundmeter;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;

import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

import net.apps123.fragment.FuPinFragment;
import net.apps123.fragment.ShengChangFragment;
import net.apps123.fragment.ShengNeng8Activity;
import net.apps123.fragment.ShengNeng8Fragment;
import net.apps123.fragment.ZengYiFragment;
import net.apps123.fragment.ZuiDaFragment;
import net.apps123.mqtt.MQClient;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.io.IOException;
import java.net.InetAddress;
import java.util.Locale;

public class KuoShengMainActivity extends AppCompatActivity {

    private FuPinFragment fuPinFragment;
    private ZengYiFragment zengYiFragment;
    private ShengChangFragment shengChangFragment;
    private ZuiDaFragment zuiDaFragment;

    private Context mContext;

    public static MqttClient mqttClient;
    //端口号
    private final int MQTT_PORT = 1883; // Broker Port
    //服务ip
    private final String MQTT_BROKER = "150.158.41.159"; // Broker URL or IP Address
    //连接地址
    private final String MQTT_URL_FORMAT = "tcp://%s:%d"; // URL Format normally don't change
    //用户id
    private final String CLINET_ID = "setApp";// client id
    //主题订阅
    private final String TOPIC = "WH-HFS-R";// a topic

    public static MqttClient getMqttClient() {
        if (mqttClient != null) {
            return mqttClient;
        }
        return null;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_kuo_sheng_main);
        mContext = this;

        initView();
        initMqtt();
    }

    private MediaPlayer mediaPlayer;
    private void playWav(View view) {
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
        }
        mediaPlayer = new MediaPlayer();
        mediaPlayer.reset();
        try {
            mediaPlayer.setDataSource(getBaseContext(), Uri.parse("android.resource://"
                    + getBaseContext().getPackageName() + "/" + R.raw.whie_noise_10s_48k));
            mediaPlayer.prepare();
            mediaPlayer.start();
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {

                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    private void initMqtt() {
        /**创建一个url*/
        String url = String.format(Locale.US, MQTT_URL_FORMAT, MQTT_BROKER, MQTT_PORT);
        /**创建一个MQClient*/
        try {
            MemoryPersistence mMemStore = new MemoryPersistence(); // On Fail reverts to MemoryStore
            mqttClient = new MQClient(url, CLINET_ID + System.currentTimeMillis(), mMemStore);
            MqttConnectOptions options = new MqttConnectOptions();
            options.setUserName("spl");
            options.setPassword("spl".toCharArray());
            mqttClient.connect();
            mqttClient.subscribe("setApp", 0);
            mqttClient.setTimeToWait(10 * 60 * 1000);

        } catch (MqttException e) {
            e.printStackTrace();
        }

    }


    private void initView() {
        String[] starArray = {"1. 传输[幅度]频率特性", "2. 传声增益", "3. 声场不均匀度", "4. 最大声压级",
                "5. 总噪声级", "6. 系统总噪声级", "7. 系统总谐波失真", "8. 早后期声能比"
        };
        ArrayAdapter<String> starAdapter = new ArrayAdapter<String>(this, R.layout.item_select, starArray);
        Spinner sp = findViewById(R.id.controlSpinner);
        sp.setPrompt("请选择操作");
        sp.setAdapter(starAdapter);
        sp.setSelection(0);

        FragmentManager fragmentManager = getSupportFragmentManager();
        sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    fragmentManager.beginTransaction().replace(R.id.fl_common_payment_replace, FuPinFragment.newInstance()).commit();
                } else if (position == 1) {
                    fragmentManager.beginTransaction().replace(R.id.fl_common_payment_replace, ZengYiFragment.newInstance()).commit();
                } else if (position == 2) {
                    fragmentManager.beginTransaction().replace(R.id.fl_common_payment_replace, ShengChangFragment.newInstance()).commit();
                } else if (position == 3) {
                    fragmentManager.beginTransaction().replace(R.id.fl_common_payment_replace, ZuiDaFragment.newInstance()).commit();
                }  else if (position == 7) {
                    fragmentManager.beginTransaction().replace(R.id.fl_common_payment_replace, ShengNeng8Fragment.newInstance()).commit();
//                    startActivity(new Intent(mContext, ShengNeng8Activity.class));
                } else {
                    fragmentManager.beginTransaction().replace(R.id.fl_common_payment_replace, ZuiDaFragment.newInstance()).commit();
                }

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });


        fuPinFragment = new FuPinFragment();
        zengYiFragment = new ZengYiFragment();
        shengChangFragment = new ShengChangFragment();
        zuiDaFragment = new ZuiDaFragment();

//        FragmentTransaction ft = getFragmentManager().beginTransaction();
//        ft.add(R.id.fragLayout, mFragmentA);
//        ft.commit();
        findViewById(R.id.backImg).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        findViewById(R.id.genBtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playWav(v);
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mqttClient != null) {
            try {
                mqttClient.disconnect();
                mqttClient.close();
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
        }
    }
}
